package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

// l1 = [2,4,3], l2 = [5,6,4]
// l1 = [0], l2 = [0]
// 342 + 465 = 807.
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {

	node := &ListNode{Val: 0, Next: nil}
	head := &ListNode{Val: 0, Next: nil}
	for l1 != nil || l2 != nil {
		if l1 != nil {
			node.Val += l1.Val
		}
		if l2 != nil {
			node.Val += l2.Val
		}
		// 进位
		if node.Val > 9 {
			node.Val -= 10
			node.Next = &ListNode{Val: 1, Next: nil}
		} else {
			node.Next = &ListNode{Val: 0, Next: nil}
		}
		l1 = l1.Next
		l2 = l2.Next
		//
		node = node.Next
		if node != nil {
			// head.Next = &ListNode{Val: 0, Next: nil}
			head.Next = node
		}
	}
	// 最后一个节点(需要返回所有节点)
	return head
}

func main() {
	l1 := &ListNode{Val: 2, Next: &ListNode{Val: 4, Next: &ListNode{Val: 3}}}
	l2 := &ListNode{Val: 5, Next: &ListNode{Val: 6, Next: &ListNode{Val: 4}}}

	// l1 := &ListNode{Val: 1, Next: &ListNode{Val: 8}}
	// l2 := &ListNode{Val: 0}

	node := addTwoNumbers(l1, l2)
	fmt.Println(node)
	for node.Next != nil {
		fmt.Println(node.Val)
		node = node.Next
	}
}
